package com.zygh.policeasset.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.util.StringUtil;
import com.zygh.policeasset.component.CommonResult;
import com.zygh.policeasset.pojo.UploadFile;
import com.zygh.policeasset.service.UploadFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.util.JSONUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping({"/uploadfile"})
@Api(tags = {"附件上传模块"})
@RestController
@CrossOrigin
public class UploadFileController {
    @Autowired
    UploadFileService uploadFileService;
    @Value("${file.FjFile}")
    String FjFile;

    @RequestMapping(value = {"/list"}, method = {RequestMethod.GET})
    @ApiOperation("获取附件列表")
    public Object getAllByRootList(@RequestParam Integer projectId,
                                   @RequestParam String projectName,
                                   @RequestParam(value = "fileType",required = false) Integer fileType) {
        if (StrUtil.isEmpty(String.valueOf(projectId))) {
            return new CommonResult().validateFailed("项目id不能为空");
        }
        if (StrUtil.isEmpty(projectName)) {
            return new CommonResult().validateFailed("类型不能为空");
        }
        if (fileType == null) {
            fileType = 0;
        }
        return this.uploadFileService.findByIdType(projectId, projectName, fileType);
    }

    @ApiOperation("上传单个文件")
    @RequestMapping(value = {"/"}, method = {RequestMethod.POST})
    public Object uploadFile(UploadFile uploadFile) {
        if (StrUtil.isEmpty(uploadFile.getProjectName())) {
            return (new CommonResult()).validateFailed("类型不能为空");
        }

        String url = null;
        String filename = null;
        MultipartFile file = uploadFile.getFile();
        if (file == null || "".equals(file) || file.getSize() == 0L) {
            return (new CommonResult()).validateFailed("文件不符合要求");
        }

        String filePath = null;
        if (uploadFile.getProjectName().equals("project")) {
            filePath = this.FjFile + uploadFile.getProjectName() + "/";
        } else {
            filePath = this.FjFile + uploadFile.getName() + "/" + uploadFile.getProjectName() + "/";
        }
        String str = DateUtil.now().replaceAll("[[\\s-:punct:]]", "");
        try {
            File path = new File(filePath);
            if (!path.getParentFile().exists())
                path.mkdirs();
            InputStream in = null;
            try {
                in = file.getInputStream();
                filename = str + "" + file.getOriginalFilename();
                filePath = filePath + "" + filename;
                File newfile = new File(filePath);
                FileUtils.copyInputStreamToFile(in, newfile);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null)
                        in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (uploadFile.getProjectName().equals("project")) {
                url = "/download/project/" + filename;
            } else {
                url = "/download/" + uploadFile.getName() + "/" + uploadFile.getProjectName() + "/" + filename;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        uploadFile.setCreateDate(DateUtil.now());
        uploadFile.setContent(url);
        Integer res = this.uploadFileService.add(uploadFile);
        System.out.println(1111111);
        if (res.intValue() > 0) {
            return (new CommonResult()).success();
        }
        return (new CommonResult()).validateFailed("上传错误");
    }

    @GetMapping({"/download/{fileName:.+}"})
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        Resource resource = this.uploadFileService.loadFileAsResource(fileName);
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException e) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header("Content-Disposition", "attachment; filename=\"" + resource.getFilename() + JSONUtils.DOUBLE_QUOTE).body(resource);
    }

    @RequestMapping(value = {"/remove"}, method = {RequestMethod.GET})
    @ApiOperation("删除附件")
    public Object remove(@RequestParam int id) {
        if (StrUtil.isEmpty(String.valueOf(id))) {
            return new CommonResult().validateFailed("id不能为空");
        }
        String url = "D:/police-assets/file/uploads/" + this.uploadFileService.findById(id).getContent().split("download/")[1];
        System.out.println(url);
        File file = new File(url);
        if (!file.exists()) {
            System.out.println("文件不存在");
        } else {
            file.delete();
        }
        if (this.uploadFileService.remove(id).intValue() > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("删除错误");
    }

    /*  JADX ERROR: JadxRuntimeException in pass: BlockProcessor
        jadx.core.utils.exceptions.JadxRuntimeException: Unreachable block: B:30:0x013b
        	at jadx.core.dex.visitors.blocks.BlockProcessor.checkForUnreachableBlocks(BlockProcessor.java:86)
        	at jadx.core.dex.visitors.blocks.BlockProcessor.processBlocksTree(BlockProcessor.java:52)
        	at jadx.core.dex.visitors.blocks.BlockProcessor.visit(BlockProcessor.java:44)
        */
    @ApiOperation("")
    @RequestMapping(value = {"/getfile"}, method = {RequestMethod.POST})
    public Object getfile(UploadFile uploadFile) {
        if (StrUtil.isEmpty(uploadFile.getProjectName())) {
            return (new CommonResult()).validateFailed("类型不能为空");
        }

        String url = null;
        String filename = null;
        MultipartFile file = uploadFile.getFile();
        if (file == null || "".equals(file) || file.getSize() == 0L) {
            return (new CommonResult()).validateFailed("文件不符合要求");
        }

        String filePath = null;
        if (uploadFile.getProjectName().equals("project")) {
            filePath = this.FjFile + uploadFile.getProjectName() + "/";
        } else {
            filePath = this.FjFile + uploadFile.getName() + "/" + uploadFile.getProjectName() + "/";
        }
        String str = DateUtil.now().replaceAll("[[\\s-:punct:]]", "");
        try {
            File path = new File(filePath);
            if (!path.getParentFile().exists())
                path.mkdirs();
            InputStream in = null;
            try {
                in = file.getInputStream();
                filename = str + "" + file.getOriginalFilename();
                filePath = filePath + "" + filename;
                File newfile = new File(filePath);
                FileUtils.copyInputStreamToFile(in, newfile);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null)
                        in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (uploadFile.getProjectName().equals("project")) {
                url = "/download/project/" + filename;
            } else {
                url = "/download/" + uploadFile.getName() + "/" + uploadFile.getProjectName() + "/" + filename;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!"".equals(filePath))
            return (new CommonResult()).success(url);
        return (new CommonResult()).validateFailed("上传错误");
    }

    @RequestMapping(value = {"/findInvoice"}, method = {RequestMethod.GET})
    @ApiOperation("获取发票图片")
    public Object findInvoice(@RequestParam(value = "assetType", required = false) String assetType,
                              @RequestParam(value = "buildNum", required = false) String buildNum,
                              @RequestParam(value = "section", required = false) Integer section) {

        if (StrUtil.isEmpty(String.valueOf(assetType))) {
            return new CommonResult().validateFailed("资产类型不能为空");
        }
        return new CommonResult().success(uploadFileService.findInvoice(assetType, buildNum, section));
    }
}